<template>
	<view class="content">
		<uni-nav-bar shadow color="#000" background-color="#ffffff" status-bar left-icon="left" right-icon="more-filled"
			title="我写的" @clickLeft="back" @clickRight="back" />
		<view class="tree">
			<view class="treeholedetail page__body max-width--mobile">
				<!-- f1背景图片 -->
				<view class="treeholebg">
					<view class="treeholebg_layer">
						<!-- f2 我写的内容 -->
						<view class="treeholedetail__box page-scrolling-element">
							<view class="treeholepaper treeholeletter treeholedetail__letter">
								<view class="treeholepaper__box">
									<view class="treeholepaper__main">
										<view class="neirong">
											<text>亲爱的陌生人：\n</text>
											<text style="margin-left: 30px;">你好！\n</text>
											<text v-if="letter.content" class="treeholecontent"
												style="margin-left: 30px;">{{ letter.content }}</text>
											<text v-else>加载中...</text>
										</view>
									</view>
									<view class="treeholeitem_person is-readonly">
										<image v-if="letter.avatar" style="height: 24px;width: 24px;margin-right: 1px;"
											:src="letter.avatar" mode="aspectFit"></image>
										<view v-else style="height: 24px;width: 24px;margin-right: 1px;"></view>
										<view class="treeholepaper__nickname text-medium">{{ letter.sign || '加载中...' }}
										</view>
									</view>
									<view class="treeholepaper_other">
										<view class="treeholepaper__meta">
											<view class="treeholeitem_time">
												{{ letter.creationTime | formatDate }}
											</view>
										</view>
									</view>
								</view>
								<!-- f2-1 下页脚 -->
								<view class="treeholepaper__tail">
									<view class="treeholepaper__tail-l">
									</view>
									<view class="treeholepaper__tail-r">
									</view>
								</view>
							</view>
							<view class="treeholedetail__del">
								<button class="del" @click="dialogToggle('alert')">
									<image class="treeholedetail__del-icon" style="height: 16px;width: 16px;"
										src="../../static/img/删除.svg" mode="aspectFit"></image>
									删除
								</button>
								<uni-popup ref="alertDialog" type="dialog">
									<uni-popup-dialog :type="msgType" cancelText="关闭" confirmText="同意" title="删除信件"
										content="删除后，信件和留言将不可恢复，确定删除该内容吗" @confirm="dialogConfirm" @close="dialogClose"
										class="del-popup"></uni-popup-dialog>
								</uni-popup>
							</view>

							<view class="treeholedetail__divider is-owner"></view>
							<view class="treeholedetail__anchor" style="padding-top: 0px; margin-top: 0px;"></view>
							<!-- 留言 抱抱  明天改成使用分段器-->
							<view class="treeholetabs treeholedetail__tabs">
								<view class="wzhtabs treeholetabs__entity">
									<button class="wzhtabs__item wzhtabs__item-real"
										:class="{ 'is-active': activeTab === 'comments' }"
										@click="changeTab('comments')">留言({{ commentsCount }})</button>
									<button class="wzhtabs__item wzhtabs__item-real"
										:class="{ 'is-active': activeTab === 'hugs' }"
										@click="changeTab('hugs')">抱抱(0)</button>
								</view>
							</view>
							<view class="dcl">
								<view class="wzhquery">
									<view v-if="activeTab === 'comments'" class="">
										<!-- 动态展示留言内容 -->
										<view class="civ3 dcl__item wzh-anim wzh-invisible wzh-fade-in-bottom"
											v-for="(comment, index) in comments" :key="index">
											<view class="civ3__header">
												<image src="../../static/img/default_avatar.70f94228.png"
													mode="aspectFill"
													style="height: 25px;width: 25px;margin-right: 5px;"></image>
												<view class="civ3__title fw-medium">
													<view class="civ3__nickname is-author">
														{{ comment.userPhone }}
													</view>
												</view>
												<view class="civ3__delete" @click="Commentdelate(comment)">
													删除
												</view>
											</view>
											<view class="civ3__main">
												<view class="wzhellipsis civ3__content"
													style="-webkit-line-clamp: 5; line-height: 27.04px; max-height: 135.2px;">
													<text class="wzhellipsis__text">{{ comment.commentText }}</text>
												</view>
											</view>
											<view class="civ3__footer">
												<text class="civ3__meta">{{ comment.creationTime | formatDate }}</text>

												<view class="civ3__op">
													<image src="../../static/img/icon_回复1-线 (1).png" mode="aspectFill"
														style="height: 20px;width: 20px;"
														class="civ3__op-btn is-comment">
													</image>
													<image src="../../static/img/点赞 (1).png" mode="aspectFit"
														style="height: 22px;width: 22px;" class="civ3__op-btn is-like">
													</image>
												</view>
											</view>
										</view>
									</view>
									<view v-else-if="activeTab === 'hugs'" class="wzhquery__nodata">
										暂时没有收到抱抱，给自己一个温暖的拥抱吧！
										<!-- 动态展示抱抱的内容 -->
									</view>
								</view>
							</view>
						</view>
						<!-- 发表留言 抱抱自己 -->
						<view class="businesspinbox__realbody businesspinbox__fixed">
							<view class="treeholefooter">
								<view class="treeholedetail__tools">
									<view class="treeholeop treeholedetail__op">
										<view class="treeholeop__btn fontwi" @click="OnClickLeave()">
											<image src="/static/img/信息、消息、留言.svg" mode="aspectFit"
												style="height: 17px;width: 17px;right: 5px;"></image>
											发表留言
										</view>
										<view class="treeholeop__btn  fontwi is-owner">
											<image src="/static/img/爱心.svg" mode="aspectFit"
												style="height: 17px;width: 17px;right: 5px;">
											</image>
											抱抱自己
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>
<script>
	export default {
		data() {
			return {
				letter: {},
				msgType: '',
				isDataLoaded: false, // 添加一个标志位，表示数据是否已加载
				activeTab: 'comments',
				messageId: null,
				comments: [],
				commentsCount: 0, // 用于存储留言数量
			}
		},
		onLoad(options) {
			if (!options || !options.messageId) {
				console.error('消息ID缺失或未定义');
				return;
			}
			console.log('接收到的消息ID:', options.messageId);
			if (!isNaN(options.messageId)) {
				this.messageId = options.messageId; // 存储消息ID
				this.getLetterDetail(parseInt(options.messageId, 10));
				this.getCommentsForMessage(parseInt(options.messageId, 10)); // 获取评论数据
				this.fetchCommentsCount(); // 新增获取评论数量
			} else {
				console.error('无效的消息ID参数');
			}
		},
		filters: {
			formatDate(value) {
				const date = new Date(value);
				return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
			}
		},
		methods: {
			OnClickLeave() {
				if (!this.messageId) {
					console.error('消息ID未定义，无法跳转');
					return;
				}
				console.log('传递的消息ID:', this.messageId);
				uni.navigateTo({
					url: `/pages/leave/leave?messageId=${this.messageId}` // 修正URL拼接
				});
			},
			back() {
				console.log("返回");
				uni.redirectTo({
					url: '/pages/mailbox/mailbox'
				})
			},
			getLetterDetail(messageId) {
				const url = `http://localhost:8080/letter/messages/detail/${messageId}`;
				console.log('正在从服务器获取信件详情:', url);
				uni.request({
					url: url,
					method: 'GET',
					success: (res) => {
						console.log('接收到的响应:', res);
						if (res.statusCode === 200 && res.data) {
							this.letter = {
								...res.data,
								id: res.data.messageID, // 确保从响应中提取正确的 ID
								timestamp: new Date(res.data.creationTime)
							};
							this.isDataLoaded = true;
							const data = res.data.data;
							this.letter.content = data.content;
							this.letter.avatar = data.avatar;
							this.letter.sign = data.sign;
							this.letter.creationTime = data.creationTime;
							this.letter.id = data.messageID;
						} else {
							console.warn('接收到无效的数据:', res);
						}
					},
					fail: (err) => {
						console.error('获取信件详情失败:', err);
					}
				});
			},
			dialogConfirm() {
				console.log('点击确认');
				this.deleteLetter(); // 调用删除方法
			},
			deleteLetter() {
				if (!this.letter || !this.letter.id) {
					uni.showToast({
						title: '无法获取消息ID',
						icon: 'none',
						duration: 2000
					});
					return;
				}
				const url = `http://localhost:8080/letter/messages/delete/${this.letter.id}`;
				console.log('删除请求URL:', url);

				uni.showLoading({
					title: '正在删除...',
					mask: true
				});

				uni.request({
					url: url,
					method: 'DELETE',
					success: (res) => {
						uni.hideLoading();
						if (res.statusCode === 200) {
							uni.showToast({
								title: '删除成功',
								icon: 'success',
								duration: 2000
							});
							uni.reLaunch({
								url: '/pages/index/index'
							});
						} else {
							uni.showToast({
								title: '删除失败',
								icon: 'none',
								duration: 2000
							});
						}
					},
					fail: (err) => {
						uni.hideLoading();
						uni.showToast({
							title: '请求失败',
							icon: 'none',
							duration: 2000
						});
						console.error('删除请求失败:', err);
					}
				});
			},
			dialogToggle(type) {
				this.msgType = type;
				this.$refs.alertDialog.open();
			},
			dialogClose() {
				console.log('点击关闭');
				this.$refs.alertDialog.close();
			},
			changeTab(tabName) {
				this.activeTab = tabName;
				if (tabName === 'comments') {
					this.fetchCommentsCount(); // 如果切换到留言标签，可以再次获取留言数量以保持最新
				}
			},
			getCommentsForMessage(messageId) {
				const url = `http://localhost:8080/letter/comments/listByLetterId/${messageId}`;
				console.log('正在从服务器获取评论:', url);
				uni.request({
					url: url,
					method: 'GET',
					success: (res) => {
						console.log('接收到的评论响应:', res);
						if (res.statusCode === 200 && res.data && res.data.rows) {
							this.comments = res.data.rows.map(comment => ({
								...comment,
								creationTime: comment.creationTime
							}));
						} else {
							console.warn('接收到无效的评论数据:', res);
						}
					},
					fail: (err) => {
						console.error('获取评论失败:', err);
					}
				});
			},
			fetchCommentsCount() {
				if (!this.messageId) {
					console.error('消息ID未定义，无法获取留言数量');
					return;
				}

				const url = `http://localhost:8080/letter/comments/countByMessageId/${this.messageId}`;
				uni.request({
					url: url,
					method: 'GET',
					success: (res) => {
						if (res.statusCode === 200 && res.data) {
							
							const responseData = res.data;
							if (responseData.code === 200 && responseData.data !== undefined) {
								this.commentsCount = responseData.data;
								console.log('留言数量获取成功:', this.commentsCount);
							}
						}
					},
					fail: (err) => {
						console.error('获取留言数量失败:', err);
					}
				});
			},
			Commentdelate(comment) {
				// 检查 comment.id 是否存在且非 undefined 或 null
				if (!comment || typeof comment.id === 'undefined' || comment.id === null) {
					uni.showToast({
						title: '评论ID无效',
						icon: 'none',
						duration: 2000
					});
					return;
				}

				console.log('尝试删除的评论ID:', comment.id);

				const url = `http://localhost:8080/letter/comments/delete/${comment.id}`;

				uni.showLoading({
					title: '正在删除...',
					mask: true
				});

				uni.request({
					url: url,
					method: 'DELETE',
					success: (res) => {
						uni.hideLoading();
						if (res.statusCode === 200) {
							console.log('后端返回的信息:', res.data);
							uni.showToast({
								title: '删除成功',
								icon: 'success',
								duration: 2000
							});
							this.comments = this.comments.filter(c => c.id !== comment.id);
							this.fetchCommentsCount(); // 评论删除后重新获取评论数量
						} else {
							uni.showToast({
								title: '删除失败',
								icon: 'none',
								duration: 2000
							});
						}
					},
					fail: (err) => {
						uni.hideLoading();
						uni.showToast({
							title: '请求失败',
							icon: 'none',
							duration: 2000
						});
						console.error('删除请求失败:', err);
					}
				});
			}
		}
	}
</script>

<style lang="scss">
	// .tree{
	//     position: absolute;
	//     left: 0;
	//     right: 0;
	//     top: 0;
	//     bottom: 0;
	//     overflow-y: auto;
	//     -webkit-overflow-scrolling: touch;
	// }
	.treeholebg {
		position: relative;
		left: 0;
		right: 0;
		top: -2px;
		bottom: 0;
		min-height: 100vh;
		overflow: hidden;
		background: #13213c;
	}

	.treeholebg_layer {
		position: relative;
		left: 0;
		right: 0;
		top: 0;
	}

	.treeholebg_layer {
		bottom: 0;
		height: 1500rpx;
		background-image: url();
		background-repeat: no-repeat;
		background-position: top;
		background-size: 100% auto;
	}

	.treeholedetail__box {
		position: relative;
		max-width: 390px;
		margin: 0 auto;

	}

	.treeholedetail__box {
		position: absolute;
		left: 0;
		right: 0;
		top: 0;
		bottom: 0;
		overflow-y: auto;

	}

	.treeholedetail__letter {
		position: relative;
		z-index: 0;
		margin: 20px 20px 30px;
	}

	.treeholepaper {
		border-radius: 5px;
		overflow: hidden;
		color: #523d14;
	}

	.treeholepaper__box {
		padding: 23px 16px 8px;
		background: #fffbea;
	}

	.treeholepaper__main>* {
		position: relative;
		z-index: 1;
	}

	.neirong {
		position: relative;
	}

	.treeholepaper__main {
		position: relative;
		margin: 0 2px;
		padding: 0 0 48px;
		font-size: 17px;
		line-height: 44px;
		background-image: linear-gradient(0deg, #e0cbab 1px, #fffbea 0);
		background-size: 100% 44px;
		background-position: 0 0;
		background-repeat: repeat-y;
		overflow-y: auto;
	}

	.treeholepaper__main:before {
		content: "";
		position: absolute;
		left: 0;
		right: 0;
		top: 0;
		bottom: 0;
		background-image: linear-gradient(90deg, rgba(0, 0, 0, 0) 40%, #fffbea 0);
		background-size: 8px 100%;
		background-position: 0 0;
		background-repeat: repeat-x;
	}

	.treeholecontent {
		white-space: pre-wrap;
		word-break: break-all;

	}

	.treeholeitem_person.is-readonly {
		cursor: inherit;
	}

	.treeholeitem_person {
		display: fixed;
		-webkit-box-pack: end;
		justify-content: flex-end;
		-webkit-box-align: center;
		align-items: center;
		max-width: 100%;
		width: fit-content;
		margin: 20px 0 0 auto;
		font-size: 17px;
		text-align: right;
		overflow: hidden;
	}

	.text-medium {
		font-weight: 600;
		font-size: 16px;
	}

	.treeholepaper__nickname {
		white-space: nowrap;
		overflow: hidden;
		-o-text-overflow: ellipsis;
		text-overflow: ellipsis;
	}

	.treeholepaper_other {
		display: flex;
		-webkit-box-align: center;
		align-items: center;
		margin: 4px 0 0;
		line-height: 1.05;
	}

	.treeholepaper__meta {
		-webkit-box-flex: 1;
		flex-grow: 1;
	}

	.treeholeitem_time {
		margin-left: 2px;
		text-align: right;
		white-space: nowrap;
		font-size: 15px;
	}

	.treeholepaper__tail {
		display: flex;
	}

	.treeholepaper__tail-l {
		position: relative;
		z-index: 1;

		-ms-flex-negative: 0;
		flex-shrink: 0;
		width: 24px;
		height: 24px;
		background-image: url();
		background-size: 100% 100%;
		background-repeat: no-repeat;
	}

	.treeholepaper__tail-r {
		-webkit-box-flex: 1;
		flex-grow: 1;
		height: 24px;
		margin-left: -2px;
		background: #fffbea;
	}


	.treeholedetail__del {
		display: -webkit-box;
		display: -webkit-flex;
		display: -ms-flexbox;
		display: flex;
		-webkit-box-align: center;
		-webkit-align-items: center;
		-ms-flex-align: center;
		align-items: center;
		-webkit-box-pack: start;
		-webkit-justify-content: flex-start;
		-ms-flex-pack: start;
		justify-content: flex-start;
		width: -webkit-fit-content;
		width: -moz-fit-content;
		width: fit-content;
		margin: .036rem .032rem 0;
		font-size: .028rem;
		color: hsla(0, 0%, 100%, .6);
		-webkit-user-select: none;
		-moz-user-select: none;
		-ms-user-select: none;
		user-select: none;
		-webkit-appearance: none;
		-moz-appearance: none;
		appearance: none;
	}

	.del {
		background-color: transparent;
		color: #cdcdcd;
		font-size: 16px;

	}

	.del::after {
		border: none;
	}

	.treeholedetail__del-icon {
		display: inline-block;
		margin-right: 6px;
		font-size: 20px;

	}

	.del-popup {
		background-color: #fffbea;
	}

	.uni-popup-dialog.uni-button-color {
		color: #000;
	}


	.del-popup .uni-popup-dialog__title {
		font-size: 18px;
		/* 标题字体大小 */
		font-weight: bold;
		/* 加粗标题 */
	}

	.treeholedetail__divider {
		margin: 30px 0 0;
	}

	.treeholedetail__divider {
		height: 8px;
		border: 0;
		background: rgba(7, 7, 7, 0.2);
	}

	.treeholedetail__tabs {
		margin: 0 20px;
	}

	.treeholedetail__tabs .wzhtabs {
		font-size: 20px;
	}

	.treeholetabs .treeholetabs__entity {
		width: 100%;
		position: relative;
		height: 54px;
	}

	.wzhtabs {
		display: flex;
	}

	.treeholetabs__entity .wzhtabs__item.is-active {
		color: #fff;
	}

	.treeholetabs__entity .wzhtabs__item {
		font-size: 17px;
		color: hsla(0, 0%, 100%, .4);
	}

	.wzhtabs__item:first-of-type {
		padding-left: 0;
	}

	.wzhtabs__item.is-active {
		font-weight: 600;
		color: var(--color-main, #1f1f1f);
	}

	.wzhtabs__item {
		-webkit-box-align: center;
		align-items: center;
		-webkit-box-pack: center;
		justify-content: center;
		height: 100%;
		padding: 0 15px;
		user-select: none;
		white-space: nowrap;
		-webkit-tap-highlight-color: transparent;
	}

	.wzhquery__nodata {
		color: hsla(0, 0%, 100%, .4);
	}

	.wzhquery__nodata {
		position: relative;
		top: 60px;
		font-size: 15px;
		left: 50px;

	}

	.businesspinbox {
		position: relative;
	}

	.businesspinbox__placeholder {
		visibility: hidden;
	}

	.businesspinbox__fixed {
		position: fixed;
	}

	.businesspinbox__realbody {
		position: absolute;
		bottom: -60px;
		left: 0;
		right: 0;
		max-width: 390px;
		margin: 0 auto;
	}

	.treeholedetail .treeholefooter {
		padding: 0;
	}

	.treeholefooter {
		position: relative;
		// padding: .012rem .032rem;
		background: #fff;
	}

	.treeholedetail__tools {
		padding: 8px 16px;
	}

	.treeholedetail__tools {
		background: #273752;
	}

	.treeholeop,
	.treeholeop__btn {

		display: flex;
		-webkit-box-align: center;
		align-items: center;
	}

	.treeholedetail__op {
		margin: 0 -20px 2px;
	}

	.treeholeop__btn {
		position: relative;
		-webkit-box-flex: 1;
		flex-grow: 1;
		flex-shrink: 0;
		-webkit-box-pack: center;
		justify-content: center;
		width: 50%;
		height: 30px;
		font-size: 15px;
		color: #fff;
		user-select: none;
		appearance: none;
	}

	.fontwi {
		font-weight: 700;
	}

	.wzhtabs__item-entity {
		display: flex;
		justify-content: space-around;
	}

	.wzhtabs__item-real {
		padding: 10px;
		margin: 0 5px;
		border: none;
		background-color: transparent;
		color: #666;
		cursor: pointer;
		outline: none;
	}

	.wzhtabs__item-real.is-active {
		background-color: transparent;
		color: #333;
		border: none;
	}

	//留言内容
	.dcl__item {
		position: relative;
		padding-top: 20px;
		padding-bottom: 10px;
	}

	.civ3 {
		color: #333;
	}

	.dcl {
		position: relative;
		z-index: 0;
		min-height: 10px;
		padding: 0 23px;
	}

	.civ3__header {
		display: -webkit-box;
		display: -webkit-flex;
		display: -ms-flexbox;
		display: flex;
		-webkit-box-align: center;
		-webkit-align-items: center;
		-ms-flex-align: center;
		align-items: center;
		-webkit-box-pack: start;
		-webkit-justify-content: flex-start;
		-ms-flex-pack: start;
		justify-content: flex-start;
		height: 22px;
	}

	.civ3__title {
		color: #fff;
	}

	.civ3__nickname,
	.civ3__title {
		-webkit-box-align: center;
		-webkit-align-items: center;
		-ms-flex-align: center;
		align-items: center;
		overflow: hidden;
	}

	.civ3__title {
		-webkit-box-flex: 1;
		-webkit-flex-grow: 1;
		-ms-flex-positive: 1;
		flex-grow: 1;
		display: -webkit-box;
		display: -webkit-flex;
		display: -ms-flexbox;
		display: flex;
		font-size: 17px;
		line-height: 1.2;
	}

	.fw-medium {
		font-weight: 700;
	}

	.civ3__delete {
		color: hsla(0, 0%, 100%, .4);
		font-size: 14px;
	}

	.civ3__main {
		margin-top: 3px;
	}

	.wzhellipsis__text {
		color: hsla(0, 0%, 100%, .8);
		font-size: 17px;
	}

	.civ3__content .wzhellipsis__text {
		white-space: pre-wrap;
	}

	.civ3__footer {
		display: -webkit-box;
		display: -webkit-flex;
		display: -ms-flexbox;
		display: flex;
		-webkit-box-align: center;
		-webkit-align-items: center;
		-ms-flex-align: center;
		align-items: center;
		margin-top: 10px;
	}

	.civ3__meta {
		font-size: 13px;
		line-height: 1.05;
		white-space: nowrap;
		color: hsla(0, 0%, 100%, .4);
	}

	.civ3__op,
	.civ3__op-btn {
		-webkit-box-align: center;
		-webkit-align-items: center;
		-ms-flex-align: center;
		align-items: center;
		-webkit-user-select: none;
		-moz-user-select: none;
		-ms-user-select: none;
		user-select: none;
	}

	.civ3__op {
		-webkit-box-flex: 1;
		-webkit-flex-grow: 1;
		-ms-flex-positive: 1;
		flex-grow: 1;
		display: -webkit-box;
		display: -webkit-flex;
		display: -ms-flexbox;
		display: flex;
		-webkit-box-pack: end;
		-webkit-justify-content: flex-end;
		-ms-flex-pack: end;
		justify-content: flex-end;
	}

	.civ3__op-btn {
		/* display: -webkit-inline-box; */
		/* display: -webkit-inline-flex; */
		display: -ms-inline-flexbox;
		display: inline-flex;
		font-size: 20px;
		line-height: 10px;
		margin-left: 20px;
		text-indent: 10px;
		/* color: #999; */
		color: hsla(0, 0%, 100%, .4);
	}

	.treeholecommentlist .civ3__op-btn {
		color: hsla(0, 0%, 100%, .4);
	}
</style>